from PyQt5 import QtWidgets
from Ui.DataLoadWindow import Ui_Dialog_Dataload
import numpy as np
import os
from PyQt5.QtCore import pyqtSignal


def LoadSingleFile(path):
    try:
        str_list = os.path.split(path)[1].split('.')[0].split('_')
        if len(str_list) <= 1:
            str_list = os.path.split(path)[1].split('-')
        col = int(str_list[2][1:])
        file_name = os.path.split(path)[1]
        if "8byte" in file_name:
            bin_file = np.fromfile(path, dtype=np.uint8)
        elif 'timeStamp' in file_name:
            cur_file = open(path, 'rb')
            # print('open curFile', file_name)
            data = cur_file.read()
            cur_file.close()
            samping = (len(data) - 4) // (4 * col * 50 + 8)
            # samping = len(data) // 4 // sensorCount
            # cicle = samping // 50
            bin_file = np.zeros((col * samping * 50), dtype=np.float32)
            for i in range(samping):
                # timebyte = struct.pack('Q', start_timestamp + 50 * i)
                # new_data[i * (sensorCount * 50 * 4 + 8) + 4: i * (sensorCount * 50 * 4 + 8) + 8 + 4] = timebyte
                temp = np.frombuffer(data[i * (col * 50 * 4 + 8) + 8 + 4: (i + 1) * (col * 50 * 4 + 8) + 4], dtype=np.float32)
                bin_file[i * 50 * col: (i + 1) * 50 * col] = temp
        else:
            bin_file = np.fromfile(path, dtype=np.float32)
        size = len(bin_file)
        row = int(size / col)
        data_array = bin_file.reshape((row, col))
        data_array_t = data_array.T
        return data_array_t
    except:
        return None


class LoadDataControl(QtWidgets.QDialog, Ui_Dialog_Dataload):
    finish = pyqtSignal()

    def __init__(self):
        super(LoadDataControl, self).__init__()
        self.setupUi(self)
        self.threads = []  # 加载数据线程,每通道一个线程
        self.joint_data = []  # 将所有bin文件拼接后的矩阵数据
        self.is_run = []

    def LoadData(self, path, index):
        size = len(path)
        joint_data = None
        if size > 0:
            for i in range(size):
                single_data = LoadSingleFile(path[i])
                if single_data is not None:
                    if joint_data is not None:
                        if joint_data.shape[0] == single_data.shape[0]:
                            joint_data = np.hstack((joint_data, single_data))
                        else:
                            joint_data = None
                            break
                    else:
                        joint_data = single_data
                else:
                    joint_data = None
                    break
            self.joint_data[index] = joint_data
        self.is_run[index] = False
        self.finish.emit()

    # def WaitForLoad(self):
    #     for t in self.threads:
    #         t.join()
